﻿var ISAUTO = true;

if(window.location.href.indexOf("mx://res/") >= 0) {
	return;
}

var rt = window.external.mxGetRuntime();
var zoomOfget = rt.storage.getConfig(window.location.host);

if(rt.storage.getConfig("isauto") == "true") {
	ISAUTO = true;
}else {
	ISAUTO = false;
}

if(zoomOfget != "") {
	//document.querySelectorAll("html")[0].style.zoom = new Number(zoomOfget);
}else {
	if(ISAUTO){
		var windowWidth = document.querySelectorAll("html")[0].offsetWidth;
		var widthk = checkAll(document.querySelectorAll("body")[0].childNodes);
		var zoom = windowWidth / widthk;
		zoom /= 1.012	
		if(zoom > 1.1)
			document.querySelectorAll("html")[0].style.zoom = zoom;
	}
	
}


function checkAll(elements) {
	for(var count = 0; count < elements.length; count++) {
		var width = elements[count].offsetWidth;
		//alert(elements.length + ":"+count+"|"+width);
		if(width < windowWidth && width != 0 && width > 800) {
			return width;
		}
	}
	for(var count = 0; count < elements.length; count++) {
		var width = checkAll(elements[count].childNodes);
		if(width > 0) {
			return width;
		}
	}
}


var browser = rt.create("mx.browser");
rt.listen("zoom", function(object) {
	var domain = window.location.host;
	var tab = browser.tabs.getCurrentTab();
	var url = tab.url;
	if(url.indexOf(domain) >= 0) {
		document.querySelectorAll("html")[0].style.zoom = object;
	}
});

rt.listen("getzoom", function() {
	var domain = window.location.host;
	var tab = browser.tabs.getCurrentTab();
	var url = tab.url;
	var object = {};
	object.zoom = document.querySelectorAll("html")[0].style.zoom;
	object.savezoom = rt.storage.getConfig(window.location.host);
	if(url.indexOf(domain) >= 0) {
		rt.post("changePanelZoom", object);
	}
});

rt.listen("savezoom", function(object) {
	// 优酷 傲游今日等获取域名不完整
	var domain = window.location.host;
	//alert(domain);
	var tab = browser.tabs.getCurrentTab();
	var url = tab.url;
		
	if(url.indexOf(domain) >= 0) {

		rt.storage.setConfig(domain, object);
	}
});

rt.listen("changeAuto", function(object) {
	ISAUTO = object;
	rt.storage.setConfig("isauto", object);
});


rt.listen("clear", function() {
	var domain = window.location.host;
	var tab = browser.tabs.getCurrentTab();
	var url = tab.url;
	if(url.indexOf(domain) >= 0) {
		rt.storage.setConfig(domain, null);
	}
});